/**
 * 
 */
package com.tamtamy.jttamobile.data.json;

import java.util.ArrayList;

import org.apache.http.ParseException;
import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;

import com.tamtamy.jttamobile.exception.NoResultException;
import com.tamtamy.jttamobile.parser.PropertyInjector;


/**
 * This factory create the object <L> that implements the list of TamTamy Object, for examples 
 * ContentList that contains Content.
 * 
 * @author mirko
 * 
 *
 * @param <L> the container list of tamtamy object 
 * @param <C> the Object returned
 */
public class JSONListFactory<L extends ArrayList<C> ,C > {
	private Class<L> lClass;
	private Class<C> cClass;
	
	public JSONListFactory(Class<L> lClass, Class<C> cClass){
		this.lClass = lClass;
		this.cClass = cClass;
	}
	
	/**
	 * Implements the creation of the List
	 * 
	 * @param jsonObject the JSON Object to parse
	 * @param listContainer the name of JSON properties that contain the list
	 * @return the object containing the List
	 * @throws NoResultException If no list is present
	 * @throws ParseException if something goes wrong
	 */
	public L createFactory( JSONObject jsonObject, String listContainer) throws NoResultException, ParseException{
		try{
	    	L list = lClass.newInstance();
			
			PropertyInjector.populateObject(list, jsonObject);
			JSONArray commentListJSON = (JSONArray)jsonObject.get(listContainer);
			if (commentListJSON == null || commentListJSON.length()==0){
				throw new NoResultException("No comments found");
			}
			for (int i = 0; i < commentListJSON.length(); i++) {
				JSONObject commentJSON = commentListJSON.getJSONObject(i);
				C comment = cClass.newInstance();
				PropertyInjector.populateObject(comment, commentJSON);
				list.add(comment);
			}		
			return list;
		}catch (NoResultException nre){
			throw nre;
		}catch(Exception e){
			Log.e(this.getClass().getSimpleName(),"Error create object",e);
			ParseException pe =  new ParseException("Unable to allocate object");
			pe.initCause(e);
			throw pe;
		}
	}
	
}
